package com.ztao.controller;

import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;
import com.ztao.pojo.Student;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Date 2024/6/7 15:34
 * @Author
 **/
@RestController
public class MongoController {
    @Resource
    private MongoTemplate mongoTemplate;

    @GetMapping("/findAll")
    public String findAll(){
      List<Student> students= mongoTemplate.findAll(Student.class);
        System.out.println(students);
        return "findAll";
    }


    //新增
    @GetMapping("/add")
    public String add() {
        Student student = new Student();
        student.setId("002");  //不写会默认生成一个  id如果存在不会新增
        student.setName2("x");
        student.setAge(2);

        Student student1 = mongoTemplate.save(student, "student");
        System.out.println(student1);
        return "save";
    }

    //删除
    @GetMapping("/remove")
    public String remove() {

        Query query = new Query(Criteria.where("name").is("x"));
        DeleteResult result = mongoTemplate.remove(query, "student");

        System.out.println(result);
        return "remove";
    }

    //修改
    @GetMapping("/update")
    public String update() {
        //1.查询
        Query query = new Query(Criteria.where("id").is("002"));
        System.out.println(query);

        //进行修改操作
        Update update = new Update().set("name", "y");
        UpdateResult result =
                mongoTemplate.updateFirst(query, update, Student.class, "student");
        System.out.println(result);
        return "update";

    }

    //查询 -根据id查询
    @GetMapping("/selectById")
    public String selectById() {

        Student student =
                mongoTemplate.findById("002", Student.class, "student");
        System.out.println(student);
        return "selectById";
    }

    //查询  -根据条件查询
    @GetMapping("/findByCondition")
    public String findByCondition() {


        Query query = new Query(Criteria.where("name").is("y"));
        List<Student> studentList =
                mongoTemplate.find(query, Student.class, "student");

        System.out.println(studentList);
        return "findByCondition";

    }
}